/**
 * 业务模块
 */
const data = require('./data.json');
const path = require('path');
const fs = require('fs');

let maxBookCode = () => {
    let arr = [];
    data.forEach((item) => {
        arr.push(item.id);
    });
    return Math.max.apply(null, arr);
};

// 主页面
exports.showIndex = (req, resp) => {
    resp.render('index', {list: data});
}

// 跳转到“添加图书”的页面
exports.toAddBook = (req,resp) => {
    resp.render('addBook', {});
}
// 添加图书（保存数据）
exports.addBook = (req,resp) => {
    let info = req.body;
    // let book = {};
    // for(let key in info) {
    //     book[key] = info[key];
    // }

    //(API) : https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
    let book = Object.assign({}, info);
    
    book.id = maxBookCode() + 1;
    data.push(book);
    fs.writeFile(path.join(__dirname,'data.json'), JSON.stringify(data,null,4), 'utf8', (err)=>{
        // if (err) throw err;
        if (err) {
            resp.send('server error');
        }
        //resp.render('index', {list: data});
        resp.redirect('/');
    });
}
exports.toEditBook = (req, resp) => {
    // (API) : http://www.expressjs.com.cn/4x/api.html#req.query
    let _id = req.query.id;
    let info = {};
    // https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Statements/for...of
    for (let item of data) {
        if(item.id == _id) {
            info = item;
            break;
        }
    }
    resp.render('editBook', {book:info});
}
exports.editBook = (req, resp) => {
    let book = req.body;
    let _id = book.id;
    for (let item of data) {
        if(item.id == _id) {
            Object.assign(item, book);
            break;
        }
    }
    fs.writeFile(path.join(__dirname,'data.json'), JSON.stringify(data,null,4), 'utf8', (err)=>{
        if (err) {
            resp.send('server error');
        }
        resp.redirect('/');
    });
}
exports.delBook = (req, resp) => {
    let _id = req.query.id;
    let _index = -1;
    for (let item of data) {
        _index ++;
        if(item.id == _id) {
            break;
        }
    }
    data.splice(_index, 1);
    fs.writeFile(path.join(__dirname,'data.json'), JSON.stringify(data,null,4), 'utf8', (err)=>{
        if (err) {
            resp.send('server error');
        }
        resp.redirect('/');
    });
}